<?php
namespace common\models\shop;

use api\modules\v1\models\shop\GoodsInfo;
use common\models\Common;
use common\models\Functions;
use common\models\im\Im;
use common\models\pay\Alipay;
use common\models\Status;
use common\models\user\User;
use common\models\address\UserAddress;
use common\models\userFund\UserMoneyLog;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use Yii;

class GoodsOrder extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%goods_order}}';
    }

    public function getOrderDetail() {
        return $this->hasMany(GoodsOrderDetail::className(), ['order_number' => 'order_number']);
    }

    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getGoods() {
        return $this->hasOne(Goods::className(), ['id' => 'goods_id']);
    }

    public function getAddress() {
        return $this->hasOne(UserAddress::className(), ['id' => 'address_id']);
    }

    public function getSell() {
        return $this->hasOne(User::className(), ['id' => 'sell_user']);
    }

    /**
     * 随机生成订单号
     * @return string
     */
    public function _createOrderNumber() {
        do {
            $orderNumber = 'GO'.date('ymdH') . rand(1000, 9999);
            $where['order_number'] = $orderNumber;
            $exist = static::getCountByWhere($where);
        } while($exist > 0);

        return $orderNumber;
    }

    /**
     * 余额支付
     * @param array $userInfo
     * @param string $orderNumber
     * @return array
     */
    public function balancePay($userInfo = [], $orderNumber = '') {
        try {

            if (empty($orderNumber)) {
                throw new Exception('未知订单');
            }

            $orderInfo = static::getOneByWhere([
                'order_number' => $orderNumber,
                'user_id' => $userInfo['id']
            ]);

            if ($userInfo['money'] < $orderInfo['money']) {
                throw new Exception('用户余额不足');
            }

            //扣钱
            UserMoneyLog::record(
                $userInfo['id'],
                Status::PROP_TYPE_MONEY,
                Status::MONEY_LOG_TYPE_BUT_GOODS,
                -1 * $orderInfo['real_money'],
                Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_BUT_GOODS] ?? '',
                "购买商品，单号：{$orderNumber}，扣除{$orderInfo['real_money']}余额。",
                $orderInfo['id']
            );

            $this->orderHandle($userInfo['id'], $orderInfo, Status::PAY_WAY_MONEY);

            return Functions::formatInside(true, '支付成功，请等待发货');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {

            return Functions::formatInside(false, $e->getMessage());
        }
    }


    /**
     * 支付宝支付
     * @param $orderNumber
     * @param $totalAmount
     * @param $payTime
     * @return array
     */
    public function aliPaySuccess($orderNumber, $totalAmount, $payTime) {
        try {

            if (empty($orderNumber)) {
                throw new Exception('未知订单');
            }

            $orderInfo = static::getOneByWhere([
                'order_number' => $orderNumber,
            ]);

            if ($orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_PAY) {
                throw new Exception('该订单已经付过款');
            }

            $this->orderHandle($orderInfo['user_id'], $orderInfo, Status::PAY_WAY_ALIPAY);

            return Functions::formatInside(true, '支付成功，请等待发货');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {

            return Functions::formatInside(false, $e->getMessage());
        }
    }

    /**
     * 支付成功之后的订单操作
     * @param $userId
     * @param $orderInfo
     * @param $payTime
     * @param $payWay
     * @throws Exception
     */
    public function orderHandle($userId = 0, $orderInfo = [], $payWay = 0, $payTime = '') {
        //1，更改订单状态
        $data['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_SEND;
        $data['pay_time'] = $payTime ? $payTime : date('Y-m-d H:i:s');//支付时间
        $data['pay_way'] = $payWay;
        $res = static::updateData($data, ['order_number' => $orderInfo['order_number']]);
        if ($res === false) {
            throw new Exception('支付失败');
        }

        if(!empty($orderInfo['sell_user'])){
            //给卖家发钱 发的是橱窗余额的钱
            UserMoneyLog::record(
                $orderInfo['sell_user'],
                Status::PROP_TYPE_SHOP_MONEY,
                Status::SHOP_MONEY_LOG_TYPE_GOODS_SELL,
                abs($orderInfo['real_money']),
                Status::SHOP_MONEY_LOG_TYPE_MAP[Status::SHOP_MONEY_LOG_TYPE_GOODS_SELL] ?? '',
//                '出售商品，用户确认收货'
                '出售商品，用户支付商品'
            );
        }

        $goodsInfo = Goods::getOneByWhere(['id' => $orderInfo['goods_id']]);

        // 发送IM消息 发给订单用户
        $userMessage = [];
        $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
        $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
        $userMessage['title'] = "订单下单通知";
        $userMessage['desc'] = "商品下单成功~";
        $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
        $userMessage['address'] = $orderInfo['address_detail'];
        $userMessage['order_number'] = $orderInfo['order_number'];
        $userMessage['order_id'] = $orderInfo['id'];
        $userMessage['time'] = date('Y-m-d H:i:s');
        $userMessage['is_sell'] = false; // 是否是自己的商品

        $config = static::getCommonByKey('shop_user_id');
        // 发给订单用户
        $userInfo = User::getOneByWhere(['id' => $orderInfo['user_id']]);
        (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);

        // 发给商品用户
        $userInfo = User::getOneByWhere(['id' => $goodsInfo['user_id']]);
        if ($userInfo) {
            $userMessage['is_sell'] = true; // 是否是自己的商品
            (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);
        }

    }

    public function finishedOrder() {
        $where['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE;
        $autoFinishedDuration = static::getCommonByKey("auto_finished_order_duration");
        $andWhere[] = ["<=", "deliver_goods_time", date("Y-m-d H:i:s", time() - $autoFinishedDuration * 60)];
        $list = static::getByAndWhere($where, $andWhere, ["id"]);
        foreach ($list as $v) {
            $this->finished($v['id']);
        }
    }

    public function finished($orderId = 0, $mark = "") {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $orderInfo = static::getOneInfoById($orderId);

            if ($orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE) {
                throw new Exception('订单未发货，不能进行完成操作');
            }

            if ($orderInfo['status'] == Status::USER_GOODS_ORDER_STATUS_DONE) {
                throw new Exception('订单已经完成，不能重复完成');
            }
            #完成订单
            $oData['status'] = Status::USER_GOODS_ORDER_STATUS_DONE;
            $oData['finished_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($oData, ['id' => $orderId]);
            if ($res === false) {
                throw new Exception("系统错误");
            }


            $goodsInfo = Goods::getOneByWhere(['id' => $orderInfo['goods_id']]);
            // 完成之后加销量
            Goods::updateAllCounters(['sale_nums' => $orderInfo['num']],['id' => $orderInfo['goods_id']]);


            // 发送IM消息
            $userMessage = [];
            $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
            $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
            $userMessage['title'] = "订单收货通知";
            $userMessage['desc'] = "商品收货成功~" . ($mark ? $mark : '');
            $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
            $userMessage['address'] = $orderInfo['address_detail'];
            $userMessage['order_number'] = $orderInfo['order_number'];
            $userMessage['order_id'] = $orderInfo['id'];
            $userMessage['time'] = date('Y-m-d H:i:s');
            $userMessage['is_sell'] = false; // 是否是自己的商品

            $config = static::getCommonByKey('shop_user_id');

            // 发给订单用户
            $userInfo = User::getOneByWhere(['id' => $orderInfo['user_id']]);
            (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);

            // 发给商品用户
            $userInfo = User::getOneByWhere(['id' => $goodsInfo['user_id']]);
            if ($userInfo) {
                $userMessage['is_sell'] = true; // 是否是自己的商品
                (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);
            }

            $trans->commit();
            return true;
        } catch (Exception $e) {
            $trans->rollBack();
            return $e->getMessage();
        }

    }

    public function cancelNotPayOrder() {
        $where['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_PAY;
        $cancelDuration = static::getCommonByKey("goods_order_auto_cancel_duration");
        $andWhere[] = ["<=", "create_time",  date("Y-m-d H:i:s", time() - $cancelDuration * 60)];

        $list = static::getByAndWhere($where, $andWhere);

        foreach ($list as $v) {

            $updateData['status'] = Status::USER_GOODS_ORDER_STATUS_CANCEL;
            $updateData['cancel_time'] = date("Y-m-d H:i:s");
            //订单状态更改
            //订单使用的券恢复

            static::updateData($updateData, ['id' => $v['id']]);
        }
    }

    public function cancelOrder($orderId = 0, $reason = '') {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $orderInfo = static::getOneInfoById($orderId);
            if (empty($orderInfo)) {
                throw new Exception('未知订单信息');
            }

            if ($orderInfo['status'] == Status::USER_GOODS_ORDER_STATUS_WAITING_SEND) {
                throw new Exception('订单已经支付，不能取消');
            }

            if ($orderInfo['status'] == Status::USER_GOODS_ORDER_STATUS_CANCEL) {
                throw new Exception('订单已经取消，不能重复取消');
            }

            if ($orderInfo['status'] == Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE) {
                throw new Exception('订单已经发货，不能取消');
            }

            if ($orderInfo['status'] == Status::USER_GOODS_ORDER_STATUS_DONE) {
                throw new Exception('订单已经完成，不能取消');
            }

            //修改订单信息
            $updateData['status'] = Status::USER_GOODS_ORDER_STATUS_CANCEL;
            $updateData['cancel_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($updateData, ['id' => $orderId]);
            if ($res === false) {
                throw new Exception('取消失败');
            }

            //加入库存
            Goods::updateAllCounters(["num" => $orderInfo['num']], ["id" => $orderInfo['goods_id']]);

            $trans->commit();
            return true;
        } catch (Exception $e) {
            return Functions::formatInside(2000, $e->getMessage());
        }
    }

    /**
     * 商家或者后台取消订单
     * @param string $orderNumber
     * @param string $reason
     * @throws Exception
     */
    public function shopOrAdminCancelOrder($orderNumber= '', $reason = '') {

        $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
        if(empty($orderInfo)) {
            throw new Exception('订单信息不存在');
        }

        if (!in_array($orderInfo['status'],[
            Status::USER_GOODS_ORDER_STATUS_WAITING_PAY,
            Status::USER_GOODS_ORDER_STATUS_WAITING_SEND,
        ])) {
            throw new Exception('该订单无法取消');
        }

        //修改订单信息
        $updateData['status'] = Status::USER_GOODS_ORDER_STATUS_CANCEL;
        $updateData['cancel_time'] = date("Y-m-d H:i:s");
        $updateData['mark'] = $reason;
        $res = static::updateData($updateData, ['id' => $orderInfo['id']]);
        if ($res === false) {
            throw new Exception('取消失败');
        }

        //加入库存
        Goods::updateAllCounters(["num" => $orderInfo['num']], ["id" => $orderInfo['goods_id']]);

        if($orderInfo['status'] == Status::USER_GOODS_ORDER_STATUS_WAITING_SEND) { //已付款需要退款
            if ($orderInfo['pay_way'] == Status::PAY_WAY_ALIPAY) {
                $alipayRes = (new Alipay())->refundGoods($orderNumber);
                if (!$alipayRes) {
                    throw new Exception('支付宝退款失败');
                }
            } else {
                // 商品退款，增加用户的余额或者原路退款
                UserMoneyLog::record(
                    $orderInfo['user_id'],
                    Status::PROP_TYPE_MONEY,
                    Status::MONEY_LOG_TYPE_BUT_GOODS_RETURN,
                    $orderInfo['real_money'],
                    Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_BUT_GOODS_RETURN] ?? '',
                    $reason
                );
            }


            if(!empty($orderInfo['sell_user'])){
                // 给卖家减少橱窗余额
                UserMoneyLog::record(
                    $orderInfo['sell_user'],
                    Status::PROP_TYPE_SHOP_MONEY,
                    Status::SHOP_MONEY_LOG_TYPE_GOODS_REFUND,
                    -1 * abs($orderInfo['real_money']),
                    Status::SHOP_MONEY_LOG_TYPE_MAP[Status::SHOP_MONEY_LOG_TYPE_GOODS_REFUND] ?? '',
                    $reason
                );
            }
        }

    }

    /**
     * 商家或者后台同意退款
     * @param int $orderId
     * @param int $status
     * @param string $reason
     * @throws Exception
     */
    public function confirmReturnOrder($orderId = 0, $status = Status::USER_GOODS_ORDER_RETURNOK, $reason = '商家同意退款') {

        $returnInfo = GoodsOrderReturn::getOneByWhere(['order_id'=>$orderId]);
        if (empty($returnInfo)) {
            throw new Exception('未发现退订信息');
        }
        $orderInfo = static::getOneByWhere(['id' => $orderId]);
        if (empty($orderInfo)) {
            throw new Exception('未发现订单信息');
        }
        $orderUserInfo = User::getOneByWhere(['id' => $orderInfo['user_id']]);
        $orderSellUserInfo = $orderInfo['sell_user'] ? User::getOneByWhere(['id' => $orderInfo['sell_user']]) : [];
        $returnMoney = $returnInfo['return_money'];

        $goodsInfo = Goods::getOneInfoById($returnInfo['goods_id']);

        // 发送IM消息 发给订单用户
        $userMessage = [];
        $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
        $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
        $config = static::getCommonByKey('shop_user_id');

        if($status == Status::USER_GOODS_ORDER_RETURNOK){ //同意退款
            //更新退款表
            $returnData['reject_time'] = date('Y-m-d H:i:s');
            $returnData['status'] = Status::USER_GOODS_ORDER_RETURNOK;
            $orderReturn = GoodsOrderReturn::updateData($returnData,['order_id'=>$orderId]);
            if($orderReturn == false){
                throw new Exception('退款状态更新失败');
            }
            //更新订单表
            $OrderData['finished_time'] = date('Y-m-d H:i:s');
            $OrderData['status'] = Status::USER_GOODS_ORDER_RETURNOK;
            $order = static::updateData($OrderData,['id'=>$orderId]);
            if($order == false){
                throw new Exception('订单状态更新失败');
            }


            if ($orderInfo['pay_way'] == Status::PAY_WAY_ALIPAY) {
                $alipayRes = (new Alipay())->refundGoods($orderInfo['order_number']);
                if (!$alipayRes) {
                    throw new Exception('支付宝退款失败');
                }
            } else {
                //商品退款
                UserMoneyLog::record(
                    $returnInfo['user_id'],
                    Status::PROP_TYPE_MONEY,
                    Status::MONEY_LOG_TYPE_BUT_GOODS_RETURN,
                    $returnMoney,
                    Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_BUT_GOODS_RETURN] ?? '',
                    $reason
                );
            }

            if(!empty($orderSellUserInfo)){
                // 给卖家减少橱窗余额
                UserMoneyLog::record(
                    $orderInfo['sell_user'],
                    Status::PROP_TYPE_SHOP_MONEY,
                    Status::SHOP_MONEY_LOG_TYPE_GOODS_REFUND,
                    -1 * abs($orderInfo['real_money']),
                    Status::SHOP_MONEY_LOG_TYPE_MAP[Status::SHOP_MONEY_LOG_TYPE_GOODS_REFUND] ?? '',
                    $reason
                );
            }


            // 发送IM消息 发给订单用户
            $userMessage['title'] = "订单退款成功";
            $userMessage['desc'] = $returnMoney;
            $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
            $userMessage['address'] = $orderInfo['address_detail'];
            $userMessage['order_number'] = $orderInfo['order_number'];
            $userMessage['order_id'] = $orderInfo['id'];
            $userMessage['time'] = date('Y-m-d H:i:s');
            $userMessage['is_sell'] = false; // 是否是自己的商品
            // 发给订单用户
            (new Im()) -> sendUserMessage($orderUserInfo['tx_code'], $userMessage, $config);

            // 发给商品用户
            if(!empty($orderSellUserInfo)){
                $userMessage['is_sell'] = true; // 是否是自己的商品
                (new Im()) -> sendUserMessage($orderSellUserInfo['tx_code'], $userMessage, $config);
            }

        }elseif ($status == Status::USER_GOODS_ORDER_RETURNNO){//驳回退款
            $reject = $reason;
            //更新状态
            if(empty($reject)){
                throw new Exception('填写驳回理由');
            }
            $returnData['reject'] = $reject;
            $returnData['reject_time'] = date('Y-m-d H:i:s');
            $returnData['status'] = Status::USER_GOODS_ORDER_RETURNNO;
            //更新退款表
            $orderReturn = GoodsOrderReturn::updateData($returnData,['order_id'=>$orderId]);
            if(!$orderReturn){
                throw new Exception('退款状态更新失败');
            }
            //更新订单表
            $order = GoodsOrder::updateData(['status'=>Status::USER_GOODS_ORDER_RETURNNO],['id'=>$orderId]);
            if(!$order){
                throw new Exception('订单状态更新失败');
            }
            $msg = '驳回成功';

            // 发送IM消息 发给订单用户
            $userMessage['title'] = "订单退款失败";
            $userMessage['desc'] = $reject;
            $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
            $userMessage['address'] = $orderInfo['address_detail'];
            $userMessage['order_number'] = $orderInfo['order_number'];
            $userMessage['order_id'] = $orderInfo['id'];
            $userMessage['time'] = date('Y-m-d H:i:s');
            $userMessage['is_sell'] = false; // 是否是自己的商品
            // 发给订单用户
            (new Im()) -> sendUserMessage($orderUserInfo['tx_code'], $userMessage, $config);

            // 发给商品用户
            if(!empty($orderSellUserInfo)){
                $userMessage['is_sell'] = true; // 是否是自己的商品
                (new Im()) -> sendUserMessage($orderSellUserInfo['tx_code'], $userMessage, $config);
            }

        }else{
            throw new Exception('参数异常');
        }
    }


    /**
     * 延迟收货
     * @param string $orderNumber
     * @throws Exception
     */
    public function extendFinished($orderNumber= '') {

        $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
        if(empty($orderInfo)) {
            throw new Exception('订单信息不存在');
        }

        if (!in_array($orderInfo['status'],[
            Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE,
        ])) {
            throw new Exception('该订单无法延迟收货');
        }

        if ($orderInfo['is_extend_confirm'] == Status::COMMON_RADIO_YES) {
            throw new Exception('该订单只能延迟收货一次');
        }

        //修改订单信息
        $updateData['is_extend_confirm'] = Status::COMMON_RADIO_YES;
        $res = static::updateData($updateData, ['id' => $orderInfo['id']]);
        if ($res === false) {
            throw new Exception('延迟失败');
        }

    }


    //自动完成订单
    public function updateOrderDone() {
        $where['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE;
        $config = static::getCommonByKey(["shop_order_done",'shop_order_extend_done']);

        $extendOrderDone = $config['shop_order_done'] + $config['shop_order_extend_done'];
        $andWhere[] = [
            'or',
            ["<=", "deliver_goods_time", date("Y-m-d H:i:s",strtotime("-{$config['shop_order_done']} days"))],
            [
                'and',
                ['=','is_extend_confirm',Status::COMMON_RADIO_YES],
                ["<=", "deliver_goods_time", date("Y-m-d H:i:s",strtotime("-{$extendOrderDone} days"))],

            ],

        ];

        $list = static::getByAndWhere($where, $andWhere, ["id"]);

        foreach ($list as $v) {
            $this->finished($v['id'],'系统自动完成');
        }
    }

    //提醒卖家发货
    public function orderRemindSend() {
        $where = $andWhere = [];

        $where['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_SEND;
        $list = static::getByAndWhere($where, $andWhere, ["id"]);

        foreach ($list as $v) {
            $this->remindSend($v['id']);
        }
    }

    public function remindSend($orderId = 0) {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $orderInfo = static::getOneInfoById($orderId);
            $goodsInfo = Goods::getOneByWhere(['id' => $orderInfo['goods_id']]);
            $time = date('Y-m-d H:i:s');

            if ($orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_SEND) {
                throw new Exception('订单已经发货，不能进行完成操作');
            }

            //判断 提醒次数
            //第一次
            if($orderInfo['remind_num'] == 0 && $time > date("Y-m-d H:i:s",strtotime("+6 hours",strtotime($orderInfo['pay_time']))) ){
                //提醒商家发货
                $this->remindMessage($orderInfo,$goodsInfo,$orderInfo['remind_num']);
            }

            //第二次
//            if($orderInfo['remind_num'] == 1 && $time > date($orderInfo['pay_time'],strtotime("+12 hours")) ){
            if($orderInfo['remind_num'] == 1 && $time > date("Y-m-d H:i:s",strtotime("+12 hours",strtotime($orderInfo['pay_time']))) ){
                //提醒商家发货
                $this->remindMessage($orderInfo,$goodsInfo,$orderInfo['remind_num']);
            }

            //第三次
//            if($orderInfo['remind_num'] == 2 && $time > date($orderInfo['pay_time'],strtotime("+18 hours")) ){
            if($orderInfo['remind_num'] == 2 && $time > date("Y-m-d H:i:s",strtotime("+18 hours",strtotime($orderInfo['pay_time']))) ){
                //提醒商家发货
                $this->remindMessage($orderInfo,$goodsInfo,$orderInfo['remind_num']);
            }

            //第四次
//            if($orderInfo['remind_num'] == 3 && $time > date($orderInfo['pay_time'],strtotime("+24 hours")) ){
            if($orderInfo['remind_num'] == 3 && $time > date("Y-m-d H:i:s",strtotime("+24 hours",strtotime($orderInfo['pay_time']))) ){

                //创建退款数据
                $data['user_id'] = $orderInfo['user_id'];
                $data['order_number'] = $orderInfo['order_number'];
                $data['goods_id'] = $orderInfo['goods_id'];
                $data['return_num'] = $orderInfo['num'];
                $data['order_id'] = $orderInfo['id'];
                $data['return_money'] = $orderInfo['real_money'];
                $data['reason'] = '未发货自动退款';
                $data['status'] = Status::USER_GOODS_ORDER_SHENQING;
                $data['create_time'] = date('Y-m-d H:i:s');
                $res = GoodsOrderReturn::insertData($data);
                if ($res == false) {
                    throw new Exception('退款订单创建失败');
                }

                //修改订单表状态
                static::updateData(['status'=>Status::USER_GOODS_ORDER_SHENQING],['order_number'=>$orderInfo['order_number']]);

                //退款 ，金额原路返回
                $this->confirmReturnOrder($orderId,Status::USER_GOODS_ORDER_RETURNOK,"商家未发货退款");
            }

            $trans->commit();
            return true;
        } catch (Exception $e) {
            $trans->rollBack();
            return $e->getMessage();
        }

    }

    /**
     *
     * @param string $orderNumber
     * @throws Exception
     */
    public function remindMessage($orderInfo= [] , $goodsInfo = [] ,$remindNum = 0) {

        $config = static::getCommonByKey('shop_user_id');
        $num = $remindNum +1;

        // 发送IM消息
        $userMessage = [];
        $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
        $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
        $userMessage['title'] = "订单未发货通知";
        $userMessage['desc'] = "订单未发货第 {$num} 次通知";
        $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
        $userMessage['address'] = $orderInfo['address_detail'];
        $userMessage['order_number'] = $orderInfo['order_number'];
        $userMessage['order_id'] = $orderInfo['id'];
        $userMessage['time'] = date('Y-m-d H:i:s');
        $userMessage['is_sell'] = false; // 是否是自己的商品
        // 发给商品用户
        $sellInfo = User::getOneByWhere(['id' => $goodsInfo['user_id']]);
        if ($sellInfo) {
            $userMessage['is_sell'] = true; // 是否是自己的商品
            (new Im()) -> sendUserMessage($sellInfo['tx_code'], $userMessage, $config);
        }

        //增加提醒次数
        static::updateAllCounters(['remind_num' => 1],['id' => $orderInfo['id']]);

    }

}


